package com.itrus.common.unittest.dbutils;

import com.itrus.common.unittest.dbutils.processor.GeneraBeanProcessor;
import jdk.jfr.Name;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.RowProcessor;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.KeyedHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import javax.inject.Inject;
import javax.inject.Named;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author zss
 * @version v4.9.2
 * 2024/5/31
 **/
@Named("dbUtilsManager")
public class DbUtilsManager {


    @Inject
    private DataSource dataSource;

    private QueryRunner queryRunner;

    public <T> T toBean(String sql, Class<T> beanClass, Map<String, String> specialColumnMap) throws SQLException {
        GeneraBeanProcessor bean = new GeneraBeanProcessor(specialColumnMap);
        RowProcessor rowProcessor = new BasicRowProcessor(bean);
        BeanHandler<T> handler = new BeanHandler<T>(beanClass, rowProcessor);
        return queryRunner.query(sql, handler);
    }

    public <T> List<T> toBeanList(String sql, Class<T> beanClass, Map<String, String> specialColumnMap) throws SQLException {
        GeneraBeanProcessor bean = new GeneraBeanProcessor(specialColumnMap);
        RowProcessor rowProcessor = new BasicRowProcessor(bean);
        BeanListHandler<T> handler = new BeanListHandler<T>(beanClass, rowProcessor);
        return queryRunner.query(sql, handler);
    }

    /**
     * 每行纪录保存到主键为key的map对象中，里面map的key为列名，value为值
     * @param sql
     * @param pkColumn 主键字段，类型为Long
     * @return
     * @throws SQLException
     */
    public Map<Long,Map<String, Object>> toKeyDataMap(String sql, String pkColumn) throws SQLException{
        return queryRunner.query(sql,  new KeyedHandler<Long>(pkColumn));
    }

    public Map<String, Object> toFieldDataMapByJdbcId(String sql) throws SQLException{
        return queryRunner.query(sql, new MapHandler());
    }

    public QueryRunner getQueryRunner() {
        if(queryRunner == null) {
            queryRunner = new QueryRunner(dataSource, true);
        }
        return queryRunner;
    }

}
